<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/2/24
 * Time: 16:17
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Page;
use Think\Think;

class FuturesUserController extends AdminController{
    /*
     * 用户管理列表
     * */
    public function index(){
        $user = M('follow');
        //经纪人搜索
        if($_REQUEST['is_agent']){
    			if($_REQUEST['is_agent']==1){
    				$map['is_agent']=array('eq',1);
    				$is_agent=1;
    			}elseif($_REQUEST['is_agent']==2){
    				$map['is_agent']=array('eq',0);
    				$is_agent=2;
    			}else{
    				$is_agent=-1;
    			}
    		}else{
    			$is_agent=-1;
    		}
        $this->assign('is_agent',$is_agent);
         //用户名搜索
         if($_REQUEST['nickname']){
            $nickname=$_REQUEST['nickname'];
            $map['nickname']=array('like',"%".trim($nickname)."%");
            $this->assign('nickname',$nickname,'','trim');
         }
          //电话号码搜索
         if($_REQUEST['mobile']){
            $mobile=$_REQUEST['mobile'];
            $map['mobile']=array('like',"%".trim($mobile)."%");
            $this->assign('mobile',$mobile,'','trim');
         }
        $map['is_futures_user'] = 1;
        //开始时间搜索
   		 if($_REQUEST['begin_time']){
             $begin_time=$_REQUEST['begin_time'];
             $map['subscribe_time']=array('egt',strtotime($begin_time));
             $this->assign('begin_time',$begin_time);
         }
         if($_REQUEST['end_time']){
             $end_time=$_REQUEST['end_time'];
             $map['subscribe_time']=array('elt',strtotime($end_time));
             $this->assign('end_time',$end_time);
         }
         if($_REQUEST['begin_time'] && $_REQUEST['end_time']){
             $map['subscribe_time']=array('between',strtotime($begin_time).",".(strtotime($end_time)+86400));
         }
         $map['is_futures_user'] = 1;
         if(empty( $map['mobile'])){
         	$map['mobile'] = array('neq',0);
         }
        $count      = $user->where($map)->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出

        $list = $user->where($map)->limit($Page->firstRow.','.$Page->listRows)->order('money desc')->select();

        foreach($list as $key=>$val){
            $route=explode(",",$val['route']);
            $route=array_pop($route);
            $usernameData=$user->where('id='.$route)->find();
            $list[$key]['topname']=$usernameData['nickname'];
        }
        $this->assign('list',$list);
        $this->assign('show',$show);
        $this->display();

    }
    /*
    *验证手机是否有用
    */
    private function is_mobile($string){
        if (!empty($string)) {
            return preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $string);
        }
        return FALSE;
    }
    /**
     * [modify_account 更改账户资金]
     * @param  [type] $openid [用户Openid]
     * @param  [type] $money  [操作金额]
     * @param  [type] $type   [操作类型]
     * @param  [type] $note   [操作说明]
     * @return [type]         []
     */
    function modify_account($openid,$money,$type,$note){
        $where = array();
        $where['openid'] = $openid;
        $user = M('Follow')->field('id,money')->where($where)->find();
        //金额日志
        $total_money = $user['money']+$money;
        $res = M('Follow')->where($where)->setField(array('money'=>$total_money));
        if($res){
            //金额日志
            $data['user_id']=$user['id'];
            $data['money'] = $money;
            $data['type'] = $type;
            $data['note'] = $note;
            $balance = M('Follow')->where($where)->getField('money');
            $data['balance'] = $balance;
            $data['create_time'] = time();
            $res2 = M('FuturesFundRecord')->data($data)->add();
        }
    }
    /*
     * 用户管理编辑*/
    public function edit(){
         /*编辑用户*/
       if(IS_POST){
       		if($_POST['nickname'] && IS_AJAX){
       			$nickname=$_POST['nickname'];
       			$map['nickname']=array('like',"%".trim($nickname)."%");
       			$this->assign('nickname',$nickname,'','trim');
       			$map['mobile'] = array('neq',0);
       			$list = M('follow')->where($map)->field('id,nickname')->select();
       			$this->ajaxReturn($list);
       		}
       		$id = $_POST['id'];
            $userdata=M('follow')->find($id);
       		//获取所属上级的关系路由
       		$route=M('follow')->where('id='.$_POST['route'])->field('id,nickname,route')->find();
       		//设置关系路由
       		$route_str = $route['route'].','.$_POST['route'];
       		$route_str = trim($route_str,',');
       		$data['route'] = $route_str;
       		//获取所属下级
            $where['_string'] = "(route like '{$id}') or (route regexp ',{$id},') or (route regexp '^{$id},') or (route regexp ',{$id}$')";
       		$sub = M('follow')->where($where)->field('id,nickname,route')->select();
       		//判断所修改的上级是否为自己的所属下级
       		foreach($sub as $v){
       			$sub_id[] = $v['id'];
       		}
       		if(in_array($_POST['route'], $sub_id) || $_POST['route']==$id){
       			$this->error('不能修改为自己下级的所属下级');
       		}
       		//修改下级的关系路由
			foreach($sub as $v){
				$sub_str = $route_str.','.substr($v['route'],strrpos($v['route'],$id));
				$sub_str = trim($sub_str,',');
				$sub_data['route'] = $sub_str;
				$user = M('follow')->where('id = '.$v[id])->save($sub_data);
			}
            $edit_where['id']=I('post.id');
            //修改是否经纪人
            $agent =I('post.is_agent');
            //修改密码
            $password=I('post.futures_pwd');
            $repassword = I('post.refutures_pwd');
           /*比对两次密码输入是否一致*/
           if($password!== $repassword){
               $this->error('您输入的新密码与确认密码不一致');
           }
            $mo = I('post.mobile');
            if(!$this->is_mobile($mo)){
               $this->error('电话号码不能为空');
            }
            //判断密码不为空就写入到数据库
            if(!empty($futures_pwd)){
                $futures_pwd=md5($password.$edit_where['id']);
                $data['futures_pwd'] = $futures_pwd;
            }
            $data['mobile']=$mo;
            $data['is_agent']= $agent;
           $user = M('follow')->where($edit_where)->save($data);
            if($user===false){
                $this->error('编辑失败');
            }else{
                $this->success('编辑成功',U('FuturesUser/index'));
                $this->edit_level_log($id,$_POST['route'],$userdata,$route['nickname']);
            }
        }else{
           /*查询显示*/
           $id=I('get.id');
           $data=M('follow')->where("id='".$id."'")->find();
		   //获取上级
    	   $string = $data['route'];//strrpos()
           $route = substr($string,strrpos($string,','));
           $route = ltrim($route,',');
           //获取已注册的用户
           $list=M('follow')->where('mobile != 0')->field('id,nickname')->select();

           $this->assign('route',$route);
           $this->assign('list',$list);
           $this->assign('data',$data);
           $this->display();
       }

    }
    /*查询上级*/
    /* public function ajax(){
    	//用户名搜索
	    $nickname=$_POST['route'];
	    $map['nickname']=array('like',"%".trim($nickname)."%");
	    $this->assign('nickname',$nickname,'','trim');
    	$map['mobile'] = array('neq',0);
    	$list = M('follow')->where($map)->field('id,nickname')->select();
    	$this->ajaxReturn($list);
    } */
    /*查看银行卡功能*/
    public function bank(){
        /*编辑银行卡详细内容*/
        if(IS_POST){
             $id=I('post.id');
             $bank_realname = I('post.bank_realname');
             if(empty($bank_realname)){
              $this->error('银行卡名称不能为空');
              }
             $bank_card = I('post.bank_card');
             if(empty($bank_card)){
              $this->error('银行卡账号不能为空');
             }
             $id_card = I('post.id_card');
             if(empty($id_card)){
              $this->error('身份证号码不能为空');
             }
             $bank_name = I('post.bank_name');
             if(empty($bank_name)){
              $this->error('银行名称不能为空');
             }
             $pro_name= I('post.pro_name');
             if(empty($pro_name)){
              $this->error('省会不能为空');
             }
             $city_name= I('post.city_name');
             if(empty($city_name)){
              $this->error('城市不能为空');
             }
             $outlets_name = I('post.outlets_name');
             if(empty($outlets_name)){
              $this->error('开户银行地址不能为空');
             }
            $data['bank_realname'] = $bank_realname;
            $data['bank_card'] = $bank_card;
            $data['id_card'] = $id_card;
            $data['bank_name'] = $bank_name;
            $data['pro_name'] = $pro_name;
            $data['city_name'] = $city_name;
            $data['outlets_name'] = $outlets_name;
            $ewhere['id'] = $id;
            if($id){
              $res = M('futures_user_bank')->where($ewhere)->save($data);
            }else{
              $data['user_id'] = I('post.user_id');
              $data['add_time'] = time();
              $res = M('futures_user_bank')->data($data)->add();
            }
           if($res===false){
               $this->error('编辑失败');
           }else{
               $this->success('编辑成功',U('FuturesUser/index'));
           }
        }else{
            $id=I('get.id');
            /*查出用户名字*/
            $fow = M('follow');
            $ages = $fow->where("id='".$id."'")->find();
            $this->assign('ages',$ages);
            /*用户银行卡详细*/
            $bank = M('futures_user_bank');
            $list = $bank->where("user_id='".$id."'")->find();
            $this->assign('list',$list);
            //print_r($list);exit;
            $this->display();
        }
    }
    /*银行卡删除*/
    public function bank_delete($id){
      $data['user_id'] = 0;
      $del = M('futures_user_bank')->where('id = '.$id)->save($data);
      if($del){
        $this->success('删除成功',U('FuturesUser/index'));
      }else{
        $this->error("删除失败");
      }
    }
    /*账户资金*/
    public function record(){
        if(IS_POST){
            $uid = I('post.uid');
            $openid = M('Follow')->where('id='.$uid)->getField('openid');
            $money = I('post.money');
            $note = I('post.note');
            if(empty($note)){
                $this->error('交易操作说明不能为空');
            }
            $this->modify_account($openid,$money,7,$note);
            $this->success('操作成功！');
        }else{
            $id=I('get.id');
            $fow = M('follow');
            $user = $fow->where("id='".$id."'")->find();
            $this->assign('user',$user);
            $this->display();
        }
    }
    //查看下级
    public function level(){
        $id=I('get.id');
        $lv=I('get.lv');
        $model=M('Follow');
        //匹配任意级数
        $where['_string'] = "(route like '{$id}') or (route regexp ',{$id},') or (route regexp '^{$id},') or (route regexp ',{$id}$')";
        $where['mobile'] = array('neq',0);
        //数据分页
        $count=$model->where($where)->count();
        $page=new \Think\Page($count,20);
        $show=$page->show();
        $data=$model->field('id,openid,nickname,mobile,route,money')
        ->where($where)->limit($page->firstRow.','.$page->listRows)
        ->order('money desc')->select();
        $data_count = count($data);		//统计数量
        foreach($data as $key=>$value){
            //每个用户的上级
            $rou = explode(',',$value['route']); //分割用户route
            $top=array_pop($rou);
            $topname=$model->field('nickname')->where('id='.$top)->find();
            $data[$key]['topname']=$topname['nickname'];
            //判断每个用户的级数
            $routes = explode(',',$value['route']); //分割用户route
            krsort($routes);
            $routes = array_values($routes);
            $routes = array_flip($routes);
            $data[$key]['level'] = $routes[$id]+1;  //级数
            $commissions=$model->field('a.id,a.openid,a.nickname,a.mobile,sum(b.commission) as commission,b.status')->alias('a')->join('left join wp_futures_commission b on a.id=b.commission_user_id')->where('a.id='.$value['id'])->group('status')->select();
            $data[$key]['wei'] = $commissions[0]['commission'];
            $data[$key]['yi'] = $commissions[1]['commission'];
            if($lv && ($data[$key]['level']!=$lv)){
              unset($data[$key]);
            }
        }
        $this->sortArrByField($data,'money');
        $arr = $data;
        $username=$model->field('nickname')->where('id='.$id)->find();

        $this->assign('data_count',$data_count);
        $this->assign('arr',$arr);
        $this->assign('username',$username);
        $this->assign('lv',$lv);
        $this->assign('id',$id);
        $this->assign('show',$show);
        $this->display();
    }


    function sortArrByField(&$array, $field, $desc = false){
      $fieldArr = array();
      foreach ($array as $k => $v) {
        $fieldArr[$k] = $v[$field];
      }
      $sort = $desc == false ? SORT_DESC  : SORT_ASC;
      array_multisort($fieldArr, $sort, $array);
    }

    public function agent(){
      if(IS_POST){
          $id=I('post.id');
          $role=I('post.role');
          $user_name=I('post.username');
          $password=I('post.password');
          if(empty($user_name)){
            $this->error('对不起,用户名不能为空');
          }
          if(empty($password)){
            $this->error('对不起,密码不能为空');
          }
          //代理商数据
          $data=array(
             'user_id'=>$id,
             'user_name'=>$user_name,
             'password'=>md5($password),
             'pt_role'=>$role,
             'market'=>"",
             'sure_money'=>"",
             'water'=>"",
          );
          //做市商数据
          if($role==2){
             $market=I('post.zuoshi');
             $data['market']=$market/100;

             $sure_money=I('post.sure_money');
             $data['sure_money']=$sure_money;

             $liushui=I('post.liushui');
             $data['water']=$liushui/100;
             //添加做市商时,其下级所有用户maker_id更新为做市商的id
              $where['_string'] = "(route like '{$id}') or (route regexp ',{$id},') or (route regexp '^{$id},') or (route regexp ',{$id}$')";
             $zuodata=M('Follow')->where($where)->select();
             foreach($zuodata as $val){
                  $upData['maker_id']=$id;
                  M('Follow')->where('id='.$val['id'])->save($upData);
             }

          }

        $res=M('Futures_agent')->where('user_id='.$id)->find();
        if($password==$res['password']){
            $data['password']=$res['password'];
        }
        //编辑
        if($res){
            $wherepan['user_name']=$user_name;
            $wherepan['user_id']=array('neq',$id);
            $pandata=M('Futures_agent')->where($wherepan)->select();
            if($pandata){
                $this->error('对不起用户名已存在');
            }
            $result=M('Futures_agent')->where('user_id='.$id)->save($data);
            $roledata=M('Futures_agent')->where('user_id='.$id)->find();
            if($roledata['pt_role']==1){
                //当做市商修改为代理商时其下级的maker_id更新为1；
                $where['_string'] = "(route like '{$id}') or (route regexp ',{$id},') or (route regexp '^{$id},') or (route regexp ',{$id}$')";
                $zuodata=M('Follow')->where($where)->select();
                foreach($zuodata as $val){
                    $upData['maker_id']=1;
                    M('Follow')->where('id='.$val['id'])->save($upData);
                }
            }
        }else{
            //开设
            $whereName['user_name']=$user_name;
            $userData=M('Futures_agent')->where($whereName)->find();
            if($userData){
                $this->error('对不起用户名已存在');
            }
            $data['create_time']=time();
            $result=M('Futures_agent')->add($data);
        }
        if($result!==false){
            $this->success('开设成功',U('FuturesUser/index'));
        }else{
            $this->error('开设失败');
        }
      }
      //编辑和添加时
      $id=I('get.id');
      $agentData=M('Futures_agent')->where('user_id='.$id)->find();
      if($agentData){
          $agentData['market']=$agentData['market']*100;
          $agentData['water']=$agentData['water']*100;
          $this->assign('type',1);
      }
      $this->assign('id',$id);
      $this->assign('agentData',$agentData);
      $this->display();
    }

    /*修改上级日志方法
     *
     * */
    private function edit_level_log($id,$route,$userdata,$nickname){
        //查询当前上级的id
        $before_id=array_pop(explode(',',$userdata['route']));
        if($before_id==$route){
            return false;
        }
        $bdata=M('follow')->find($before_id);
        //获取修改之后的id
        $after_id=$route;
        $user_auth = session('user_auth');
        //插入日志表中
        $data=array(
            'op_id'=>$user_auth['uid'],
            'content'=>$user_auth['username']."把".$userdata['nickname']."的上级".$bdata['nickname']."修改为".$nickname,
            'before_id'=>$before_id,
            'after_id'=>$after_id,
            'before_route'=>$userdata['route'],
            'time'=>time(),
            'edit_id'=>$id,
        );
        M('edit_level_log')->add($data);
    }

}
